<template>
  <view>
    <z-paging
      ref="paging"
      v-model="itemList"
      @query="queryList"
      :fixed="true"
      :auto="false"
      :auto-show-back-to-top="true"
      :empty-view-img="`${getImageUrl('empty.png')} `"
      empty-view-text="暂无订单数据~"
      :empty-view-img-style="imgStyle"
    >
      <view solt="top">
        <u-navbar title="消息" height="50" title-size="36"></u-navbar>
        <view class="" style="padding: 20rpx">
          <view class="message-box" @click="routeTo('/other/message-system/message-system')">
            <view class="box-left">
              <u-icon style="align-self: center" name="/static/xttz.png" size="100"></u-icon>
            </view>
            <view class="box-right">
              <view class="dis-flex flex-y-between flex-y-center">
                <view style="font-weight: 600; font-size: 32rpx">系统消息</view>
                <!-- <u-badge size="mini" :count="7" :offset="[0,-30]" type="error"></u-badge> -->
                <view class="datetime" style="font-size: 24rpx" v-if="createTime">
                  {{ $u.timeFormat(createTime, 'mm月dd日') }}
                </view>
              </view>
              <p>{{ sysMessage }}</p>
              <!-- <u-icon class="right-more" name="/static/more.png" size="25" mode=""></u-icon> -->
            </view>
          </view>
          <view
            class="message-box"
            @click="toChart(item)"
            v-for="(item, index) in itemList"
            :key="index"
          >
            <view
              class="box-left"
              style="
                height: 100rpx;
                align-self: center;
                border: 1rpx solid #efefef;
                border-radius: 10rpx;
              "
            >
              <u-image
                :src="item.data.avatar"
                width="100rpx"
                height="100rpx"
                border-radius="10"
              ></u-image>
            </view>
            <view class="box-right">
              <view class="dis-flex flex-y-between flex-y-center">
                <view class="" style="font-size: 32rpx">
                  {{ item.data.nickname }}
                </view>
                <view class="datetime">{{
                  $u.timeFormat(item.lastMessage.timestamp, 'hh:MM')
                }}</view>
              </view>
              <view class="content" style="position: relative">
                <view>{{ formatText(item.lastMessage.payload.text) }}</view>
                <u-badge size="mini" :count="item.unread" :offset="[9, 0]" type="error"></u-badge>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 	<view class="" style="padding: 20rpx;">

        </view> -->
    </z-paging>
  </view>
</template>

<script>
import { openGoEasyConnect } from '@/common/goeasy'

export default {
  data() {
    return {
      $goEasy: undefined,

      imgStyle: {
        width: '12rem'
      },
      itemList: [],
      sysMessage: '最新系统通知',
      im: null,
      createTime: ''
    }
  },
  onShow() {
    this.$goEasy = openGoEasyConnect()
    this.im = this.$goEasy.im
    const app = this
    // 加载回话列表
    this.im.latestConversations({
      onSuccess: function (result) {
        // console.log('============last============',result.content.conversations)
        let _list = [],
          _message
        result.content.conversations.forEach((message) => {
          _message = message
          let text = JSON.parse(_message.lastMessage.payload.text)
          _message.data.toShopId = text.toShopId
          _message.data.shopUserId = text.shopUserId
          if (_message.lastMessage.senderId == app.senderId) {
            _message.data.nickname = text.receiveNickname
            _message.data.avatar = text.receiveAvatar
          }
          // console.log('_message',_message)
          _list.push(_message)
        })

        app.itemList = _list
        app.initData()
      },
      onFailed: function (error) {
        //获取失败
        console.log(
          'Failed to get the latest conversations, code:' + error.code + ' content:' + error.content
        )
      }
    })
    // 监听会话列表更新
    this.im.on(this.$goEasy.IM_EVENT.CONVERSATIONS_UPDATED, function (conversations) {
      let _list = [],
        _list2 = [],
        _message
      // console.log('===========Updated======')
      conversations.conversations.forEach((message) => {
        _message = message
        let text = JSON.parse(_message.lastMessage.payload.text)
        _message.data.toShopId = text.toShopId
        _message.data.shopUserId = text.shopUserId
        if (_message.lastMessage.senderId == app.senderId) {
          _message.data.nickname = text.receiveNickname
          _message.data.avatar = text.receiveAvatar
        } else {
        }
        _list.push(_message)
      })
      app.itemList = _list
      app.initData()
    })
  },
  onHide() {
    this.$goEasy.disconnect()
  },
  onLoad() {
    this.$u.get('/app-api/system/notify-message/get-unread-list', { size: 1 }).then((res) => {
      if (res.data) {
        this.sysMessage = res.data[0]?.templateName
        this.createTime = res.data[0]?.createTime
      }
    })
    this.senderId = uni.getStorageSync('userInfo').id
  },
  methods: {
    formatText(text) {
      let _text = JSON.parse(text)
      return _text.content > 11 ? _text.content.substr(0, 11) + '...' : _text.content
    },
    initData() {
      const app = this
      app.itemList.forEach((message) => {
        // console.log('===========商家======',message.data.shopUserId,app.senderId)
        if (message.data.shopUserId != app.senderId) {
          app.$u.get('/app-api/shop/info/get', { id: message.data.toShopId }).then((res) => {
            message.data.nickname = res.data.name
            message.data.avatar = res.data.logo
          })
        }
      })
    },
    toChart(item) {
      let url = '/other/customer-chat/customer-chat?userId=' + item.userId
      if (item.data.toShopId) {
        url += '&shopId=' + item.data.toShopId
      }
      uni.navigateTo({
        url
      })
    },
    routeTo(url) {
      uni.navigateTo({ url })
    }
  }
}
</script>

<style>
page {
  background: #f7f7f7;
  padding: 20rpx;
}

.message-box {
  display: flex;
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.box-right {
  width: 100%;
  margin-top: 10rpx;
  margin-left: 15rpx;
  font-size: 33rpx;
  line-height: 47rpx;
  position: relative;
  flex: 1;
}

.box-right p {
  font-size: 28rpx;
  color: #999999;
}

.right-more {
  position: absolute;
  right: 2rpx;
  top: 35rpx;
}

.content {
  font-size: 26rpx;
  color: #999999;
  /* margin-top: 18rpx; */
}

.datetime {
  font-size: 26rpx;
  color: #999999;
}
</style>
